/*******************************
*******************************/
#include "time.h"

void Uart_TimCNT_Reload(void)
{
  TIM_Enable(TIM2, DISABLE);
  TIM2->CNT = 0;
  TIM_Enable(TIM2, ENABLE);
}


void TIM2_Init(u16 arr, u16 psc)
{
  TIM_TimeBaseInitType TIM_TimeBaseStructure;
  NVIC_InitType NVIC_InitStructure;

  RCC_EnableAPB1PeriphClk(RCC_APB1_PERIPH_TIM2, ENABLE);
  TIM_TimeBaseStructure.Period = arr;
  TIM_TimeBaseStructure.Prescaler = psc;
  TIM_TimeBaseStructure.ClkDiv = TIM_CLK_DIV1;
  TIM_TimeBaseStructure.CntMode = TIM_CNT_MODE_UP;
  TIM_InitTimeBase(TIM2, &TIM_TimeBaseStructure);

  NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
  NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  TIM_ClrIntPendingBit(TIM2, TIM_INT_UPDATE);
  TIM_ConfigInt(TIM2, TIM_INT_UPDATE, ENABLE);
  TIM_Enable(TIM2, ENABLE);
}

void TIM3_Init(u16 arr, u16 psc)
{
  TIM_TimeBaseInitType TIM_TimeBaseStructure;
  NVIC_InitType NVIC_InitStructure;

  RCC_EnableAPB1PeriphClk(RCC_APB1_PERIPH_TIM3, ENABLE);
  TIM_TimeBaseStructure.Period = arr;
  TIM_TimeBaseStructure.Prescaler = psc;
  TIM_TimeBaseStructure.ClkDiv = TIM_CLK_DIV1;
  TIM_TimeBaseStructure.CntMode = TIM_CNT_MODE_UP;
  TIM_InitTimeBase(TIM3, &TIM_TimeBaseStructure);

  NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
  NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  TIM_ClrIntPendingBit(TIM3, TIM_INT_UPDATE);
  TIM_ConfigInt(TIM3, TIM_INT_UPDATE, ENABLE);
  TIM_Enable(TIM3, ENABLE);
}

void TIM4_Init(u16 arr, u16 psc)
{
  TIM_TimeBaseInitType TIM_TimeBaseStructure;
  NVIC_InitType NVIC_InitStructure;

  RCC_EnableAPB1PeriphClk(RCC_APB1_PERIPH_TIM4, ENABLE);
  TIM_TimeBaseStructure.Period = arr;
  TIM_TimeBaseStructure.Prescaler = psc;
  TIM_TimeBaseStructure.ClkDiv = TIM_CLK_DIV1;
  TIM_TimeBaseStructure.CntMode = TIM_CNT_MODE_UP;
  TIM_InitTimeBase(TIM4, &TIM_TimeBaseStructure);

  NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
  NVIC_InitStructure.NVIC_IRQChannel = TIM4_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  TIM_ClrIntPendingBit(TIM4, TIM_INT_UPDATE);
  TIM_ConfigInt(TIM4, TIM_INT_UPDATE, ENABLE);
  TIM_Enable(TIM4, ENABLE);
}

